<template>
  <div class="accountCon">
      <div class="rightCon" :span="30">
        <el-form
          ref="detail"
          label-position="right"
          label-width="170px"
          :rules="rules"
          :model="detail"
          class="formBox"
        >
          <el-form-item label="品项组合名称:" prop="name">
            <el-input
              v-model="detail.name"
              class="w200"
              placeholder="请输入商品名称"
              :readonly="readonly"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="品项创建人:" prop="creator_name">
            <el-input
              v-model="detail.creator_name"
              class="w200"
              :readonly="true"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="品项类型:" prop="type">
            <el-cascader
              v-model="detail.type"
              :options="options.typeList"
              :disabled="readonly"
              class="w200"
              @change="changeSourceType"
            />
          </el-form-item>
          <el-form-item label="品项组合价格:" prop="price">
            <el-input
              v-model="detail.price"
              :readonly="readonly"
              type="number"
              class="w200"
               @input="val=> npChange(val,'price')"
              placeholder="请输入品项组合价格"
            />
          </el-form-item>
          <el-form-item label="品项使用次数:" prop="number">
             <el-input
              v-model="detail.number"
              :readonly="readonly"
              type="number"
              class="w200"
              @input="val=> npChange(val,'number')"
              placeholder="请输入品项使用次数"
            />
          </el-form-item>
          <el-form-item label="品项是否禁用:" prop="status">
              <el-switch
                v-model="detail.status"
                :disabled="readonly"
                :inactive-value = 1
                :active-value = 2
                active-color="#33BEA7">
              </el-switch>
          </el-form-item>
          <div style="width: 100%;">
              <el-form-item label="品项组合明细:" prop="status">
                <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    :disabled="readonly"
                    @click="handleProduct()">
                    新增
                </el-button>
              </el-form-item>
          </div>
           
        </el-form>
      </div>
      <div>
         <el-table   
         :data="goodsList"
          size="small"
          :cell-style="$style.cellStyle"
          :header-cell-style="$style.rowClass">
          <el-table-column label="产品名称" width="350">
            <template slot-scope="scope">
             <el-select
                v-model="scope.row.kingdee_code"
                :disabled="readonly"
                size="mini"
                value-key="kingdee_code"
                placeholder="请选择产品"
                filterable
                 remote
                @change="val => selectChange(val,scope.$index)"
              >
                <el-option
                  v-for="item in options.productList"
                  :key="item.kingdee_code"
                  :label="item.name"
                  :value="item.kingdee_code">
                  <span>{{ item.name }}<span style=" font-size: 13px;color: #8492a6;">--- {{ item.unit_name }}</span></span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="产品编码">
            <template slot-scope="scope">
              <span>{{scope.row.name == '' ? '--' : scope.row.kingdee_code}}</span>
            </template>
          </el-table-column>
          <el-table-column label="产品规格">
            <template slot-scope="scope">
              <span>{{scope.row.name == '' ? '--' : scope.row.spec_name == '' ? '--' : scope.row.spec_name}}</span>
            </template>
          </el-table-column>
          <el-table-column label="" width="240">
            <template slot="header">
              产品数量<div style="font-size: 8px;">（此为该组合使用此产品次数所用的产品数量）</div>
            </template>
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.number"
                class="w100"
                placeholder="请输入产品名称"
                show-word-limit
                :readonly="scope.row.id == '' || readonly"
                @input="val => numberChange(val,scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column label="产品原价">
            <template slot-scope="scope">
              <span>{{scope.row.name == '' ? '--' : scope.row.goods_price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="销售价格">
            <template slot-scope="scope">
              <span>{{scope.row.number < 1  ? '--' : scope.row.selling_price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="组合销售价">
            <template slot-scope="scope">
              <span>{{scope.row.name == '' ? '--' : scope.row.package_price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{$index}">
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                :disabled="readonly"
                circle
                @click="clickDel($index)">
              </el-button>
            </template>
          </el-table-column>
         </el-table>
      </div>
      <div class="btnBox" v-if="!readonly">
        <el-button
          type="primary"
          size="mini"
          class="mainBtn"
          @click="submitForm('detail')"
        >{{type == 'edit' ? '编辑':'新增'}}提交</el-button>
      </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { goodsGetail,editProductItem,addProductItem,getShopList,goodsTypeList,getGoodsList,miniGoodsList } from '@/api/goods';
import { convertToTreeData } from '@/utils/constants';
import { readonly } from 'vue';
class Detail {
    name='';
    number='';
    type='';
    price='';
    // applicable_shop_ids='';
    // applicable_scope='';
    creator_id = '';
    creator_name = '';
    status=1;
}
class GoodsList {
    index='';
    id ='';
    type='';
    name='';
    kingdee_code='';
    goods_price='';
    spec_name='';
    unit_name='';
    number = '';
    selling_price='';
    unit_name='';
    package_price=''
}
class Rules {
  name = [
    { required: true, message: '请填写品项名称', trigger: 'blur' }
  ];
  type = [
    { required: true, message: '请选择品项类型', trigger: 'blur' }
  ];
  number = [
    { required: true, message: '请填写次数', trigger: 'change' }
  ];
  price = [
    { required: true, message: '请填写组合价格', trigger: 'blur' }
  ];
}
class Options {
  typeList = [];
  productList = [];
  shopTypeList = [
    { label: '全部', value: 1 },
    { label: '所有门店', value: 2 },
    { label: '所有门诊', value: 3 },
    { label: '指定店铺', value: 4 }
  ];
  shopList = [];
}
export default {
  props: {

  },

  data () {
    return {
      options: new Options(), // 选项
      detail: new Detail(),
      rules: new Rules(),
      goodsList: [],  
      readonly: false,
      type: ''
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  mounted () {
    this.getOptionsList();
    if(this.$route.query.type == 'read') this.readonly = true;
    if (this.$route.query.row) {
      this.$route.query.row = JSON.parse(this.$route.query.row);
      this.detail = this.$route.query.row;
      console.log(this.detail,"qqq")
      this.detail.creator_name = this.detail.creator_name;
      this.detail.creator_id = this.detail.creator_id;
      this.type = this.$route.query.type;
      this.goodsList = this.$route.query.row.product_info;
      const { type_one, type_two, type_three } = this.$route.query.row;
      this.detail.type  = [type_one, type_two, type_three].filter(Boolean);
      console.log(this.$route.query.row, this.detail.type)
    } else{
      this.detail.creator_name = this.userInfo.realname;
      this.detail.creator_id = this.userInfo.id;
    }

  },
  methods: {
    getOptionsList(){
      goodsTypeList({type:'name'}).then(res => {
        this.options.typeList = convertToTreeData(res.data);
      })
      // miniGoodsList({status:1,page:1,limit:10000}).then(res => {
      //   this.options.productList = res.data;
      // })
      getGoodsList({search:''}).then(res => {
        this.options.productList = res.data;
      })
      // getShopList().then(res => {
      //   this.options.shopList = convertToTreeData(res.data); 
      // })
    },
    remoteMethod(e){
      getGoodsList({'search':e}).then(res => {
        this.options.productList = res.data;
      })
    },
    selectChange(val, index) {
      const selectedItem = this.options.productList.find(item => item.kingdee_code === val);
      this.goodsList[index].name = selectedItem.name;
      this.goodsList[index].id = selectedItem.id;//真正的id
      this.goodsList[index].type = selectedItem.type;
      this.goodsList[index].spec_name = selectedItem.spec_name;
      this.goodsList[index].unit_name = selectedItem.unit_name;
      this.goodsList[index].goods_price = selectedItem.goods_price;
      this.goodsList[index].number = '';
    },
    shopTypeChange(val){
      this.detail.applicable_shop_ids = [];
    },
  
    handleProduct(){
      if(this.detail.number < 1 || this.detail.price < 1){
          this.$message({
              message: '请先填写品项组合价格、品项使用次数!',
              type: 'warning'
          })
          return false;
        }

        let tip = 0
        this.goodsList.forEach(item => {
          if (item.id == '') {
            tip += 1
          }
        })
        if (tip > 0) {
          this.$message({
            message: '请补全列表中为空商品。',
            type: 'warning'
          })
        } else{
            this.goodsList.push(new GoodsList());
        }
    },
    handleChange(val) {
     
    },
    npChange(val,type){
      if(type == 'price'){
        this.detail.price = val;
        
      }else{
        this.detail.number = val;
      }
    
      this.goodsList.forEach(item => {
        item.number = '';
        item.selling_price =  '';
        item.package_price =  '';
      })
    },
    
    clickDel(index){
      this.goodsList.splice(index,1);
      this.changeSourceType();
    },
    numberChange(val,index){
      // this.goodsList[index].number = val * this.detail.number;
      this.goodsList[index].selling_price =  (Number(this.goodsList[index].number) * Number(this.goodsList[index].goods_price)).toFixed(2);

      if(this.goodsList[index].selling_price == 0){
        this.goodsList[index].package_price = 0
      }else{
        this.goodsList[index].package_price =  (Number(this.detail.price) / Number(this.goodsList[index].selling_price)).toFixed(2);
      }

      this.changeSourceType();
    },
    // 计算组合销售价
    changeSourceType(){
      let totalPrice = 0;
      this.goodsList.forEach(item => {
          const price = item.selling_price;
          totalPrice += price;
      });
      if (totalPrice > 0) {
          this.goodsList.forEach(item => {
              const price = item.selling_price;
              item.package_price = Math.round((this.detail.price / totalPrice) * price);
          });
      }
      if (this.goodsList.length > 1) {
        const sumOfPrevious = this.goodsList.slice(0, -1).reduce((sum, item) => {
          return sum + item.package_price;
        }, 0);
        const lastItem = this.goodsList[this.goodsList.length - 1];
        lastItem.package_price = Math.round(this.detail.price - sumOfPrevious);
      }
    },
    // 提交
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if(this.goodsList.length == 0) {
          this.$message({
            message: '请填写品项组合明细',
            type: 'warning' 
          })
            return false;
        }
        for (let i = 0; i < this.goodsList.length; i++) {
          if (this.goodsList[i].id == '' || this.goodsList[i].number == '') {
            this.$message({
              message: '请填写品项组合明细',
              type: 'warning'
            }) 
            return false;
          } 
        }
        if (valid) {
          this.$route.query.id?this.hint('更新'):this.hint('新建')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 提示
    hint(text){
       this.$confirm(`确定${text}此商品吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.confirm()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    // 确认提交
     confirm() {
        let product_ids = [];
        let mini_ids = [];

        this.goodsList.forEach(item => {
          if(item.type == 'goods'){
            product_ids.push(item.id) 

          }else if(item.type == 'mini'){
            mini_ids.push(item.id) 

          }

        })
        let params = {
          name:this.detail.name,
          number:this.detail.number,
          price:this.detail.price,
          // applicable_shop_ids='';
          // applicable_scope='';
          creator_id: this.userInfo.id,
          status:this.detail.status,
          type_one:this.detail.type[0],
          type_two:this.detail.type[1],
          type_three: this.detail.type[2],
          product_ids: product_ids.join(','),
          mini_ids: mini_ids.join(','),

          product_info:JSON.stringify(this.goodsList),
      
        }
       if(this.$route.query.row){
        editProductItem({...params,id: this.$route.query.row.id }).then(res => {
          this.$message({
            type: 'success',
            message: res.msg,

          });
          this.$router.push({name:'品项列表'})
        })
       }else{
         addProductItem(params).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          });
          this.$router.push({name:'品项列表'})
        })
       }


    }
  }
}
</script>

<style lang="scss" scoped>
.accountCon{
    background: #fff;
    .rightCon{
      margin-bottom: 50px;
      .formBox{
      display: flex;
      flex-wrap: wrap;
      .el-form-item{
         width: 33%;

      }
    }
    }
}
.btnBox{
  margin-top: 100px;
  text-align: center;
}
::v-deep .el-select{
  width: 300px !important;
}
::v-deep .el-input__inner{
  height: 32px;
  line-height: 32px;
}
::v-deep .el-input.is-disabled .el-input__inner{
  background-color: #fff;
  color: #606266;
}
</style>
